interface AnnualProcurementVehicle {
  // 采购车辆
  purchase_vehicle: string
  // 实际采购总金额
  sjzj: number
  // 总数量（斤数）
  zjs: number
  // 总运费
  zyf: number
}

interface AnnualSalesVehicle {
  // 销售车辆
  purchase_vehicle: string
  // 实际销售总金额
  zjatp: number
  // 实际销售总利润
  zjclr: number
}

interface SalesCustomer {
  customerId: number
  customer_name: string
  month: string
  total_actual_amount: number
  total_quantity: number
  year: number
}

interface PurchaseCustomer {
  customerId: number
  customer_name: string
  month: string
  total_actual_amount: number
  total_quantity: number
  year: number
}

interface PurchaseInfoParams {
  // 当前年份
  yearId: number
  // 客户ID
  customerId: number
}

interface CustomerModelParams {
  // 客户ID
  customerId: number
  // 当前年份
  yearId: number
}

type PurchaseInfoParam = Partial<PurchaseInfoParams>

type CustomerModelParam = Partial<CustomerModelParams>

// 获取特定年份下不同采购车辆的实际采购总金额、总数量、总运费
// Duplicate definition removed; see the single export below.

// 获取特定年份下不同车辆的实际销售总金额、总利润
export async function getActualSalesOfVehicles(params?: PurchaseInfoParam) {
  return usePost<AnnualSalesVehicle[]>('/common/getActualSalesOfVehicles', params, {
    loading: true,
  })
}

// 依据年份、客户ID获取不同客户采购总金额和斤数
export async function getPurchaseListOfYear(params?: CustomerModelParam) {
  return usePost<PurchaseCustomer[]>('/common/getPurchaseListOfYear', params, {
    loading: true,
  })
}

// 依据年份、客户ID获取不同客户销售总金额和斤数
export async function getSalesListOfYear(params?: CustomerModelParam) {
  return usePost<SalesCustomer[]>('/common/getSalesListOfYear', params, {
    loading: true,
  })
}


// 别名 API：为 H5 组件提供期望的数据结构
function normalizeMonthToIndex(monthInput: any): number {
  // 统一为字符串处理，兼容数字与多种格式：1、"1月"、"01"、"2024-01"、202401
  const s = String(monthInput ?? '').trim()
  if (!s) return -1
  const digits = s.replace(/[^0-9]/g, '')
  if (!digits) return -1
  const n = parseInt(digits, 10)
  if (!Number.isFinite(n)) return -1
  const mm = n > 100 ? n % 100 : n
  return mm >= 1 && mm <= 12 ? mm : -1
}

// 新增：将后端可能返回的字符串数值安全转换为 number
function toNumber(input: any): number {
  const n = typeof input === 'number' ? input : parseFloat(String(input ?? '').trim())
  return Number.isFinite(n) ? n : 0
}

const MONTH_LABELS = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']

// 依据年份、客户ID获取不同客户销售总金额和斤数，用于绘制年度销售趋势图
export async function getAnnualSales(params?: CustomerModelParam) {
  const res = await getSalesListOfYear(params)
  const list: any[] = Array.isArray((res as any)?.data) ? (res as any).data : []
  const acc: Record<number, number> = {}
  for (const item of list) {
    const idx = normalizeMonthToIndex(item.month)
    const v = toNumber(item.total_actual_amount)
    if (idx !== -1) acc[idx] = (acc[idx] ?? 0) + v
  }
  const data = MONTH_LABELS.map((label, i) => ({ month: label, value: acc[i + 1] ?? 0 }))
  return { ...(res as any), data }
}

// 依据年份、客户ID获取不同客户采购总金额和斤数，用于绘制年度采购趋势图
export async function getAnnualProcurement(params?: CustomerModelParam) {
  const res = await getPurchaseListOfYear(params)
  const list: any[] = Array.isArray((res as any)?.data) ? (res as any).data : []
  const acc: Record<number, number> = {}
  for (const item of list) {
    const idx = normalizeMonthToIndex(item.month)
    const v = toNumber(item.total_actual_amount)
    if (idx !== -1) acc[idx] = (acc[idx] ?? 0) + v
  }
  const data = MONTH_LABELS.map((label, i) => ({ month: label, value: acc[i + 1] ?? 0 }))
  return { ...(res as any), data }
}

// 依据年份、客户ID获取不同客户销售总金额和斤数，用于绘制年度销售趋势图
export async function getAnnualSalesOfVehicles(params?: PurchaseInfoParam) {
  const res = await getActualSalesOfVehicles(params)
  const data = Array.isArray((res as any)?.data)
    ? (res as any).data.map((item: any) => ({
        name: item.purchase_vehicle,
        value: toNumber(item.zjatp),
      }))
    : []
  return { ...(res as any), data }
}

// 依据年份、客户ID获取不同客户销售总金额和斤数，用于绘制年度销售趋势图（按客户聚合）
export async function getAnnualSalesByCustomer(params?: CustomerModelParam) {
  // 使用实际存在的后端接口，并按客户聚合全年销售总金额/斤数
  const res = await getSalesListOfYear(params)
  const list: any[] = Array.isArray((res as any)?.data) ? (res as any).data : []
  const acc: Record<string, { amount: number; quantity: number }> = {}
  for (const item of list) {
    const name = item.customer_name
    const amount = toNumber(item.total_actual_amount)
    const quantity = toNumber(item.total_quantity)
    const prev = acc[name] || { amount: 0, quantity: 0 }
    acc[name] = { amount: prev.amount + amount, quantity: prev.quantity + quantity }
  }
  const data = Object.keys(acc).map(name => ({
    name,
    amount: acc[name].amount,
    quantity: acc[name].quantity,
  }))
  return { ...(res as any), data }
}

// 依据年份、客户ID获取不同客户采购总金额和斤数，用于绘制年度采购趋势图（按客户聚合）
export async function getAnnualProcurementByCustomer(params?: CustomerModelParam) {
  // 使用实际存在的后端接口，并按客户聚合全年采购总金额/斤数
  const res = await getPurchaseListOfYear(params)
  const list: any[] = Array.isArray((res as any)?.data) ? (res as any).data : []
  const acc: Record<string, { amount: number; quantity: number }> = {}
  for (const item of list) {
    const name = item.customer_name
    const amount = toNumber(item.total_actual_amount)
    const quantity = toNumber(item.total_quantity)
    const prev = acc[name] || { amount: 0, quantity: 0 }
    acc[name] = { amount: prev.amount + amount, quantity: prev.quantity + quantity }
  }
  const data = Object.keys(acc).map(name => ({
    name,
    amount: acc[name].amount,
    quantity: acc[name].quantity,
  }))
  return { ...(res as any), data }
}

// 依据年份、客户ID获取不同客户采购总金额和斤数，用于绘制年度采购趋势图（按车辆聚合）
export async function getAnnualProcurementOfVehicles(params?: PurchaseInfoParam) {
  // 返回结构统一为 H5 组件期望的 { name, value }
  const res = await usePost<any[]>('/common/getAnnualProcurementOfVehicles', params, {
    loading: true,
  })
  const data = Array.isArray((res as any)?.data)
    ? (res as any).data.map((item: any) => ({
        name: item.purchase_vehicle,
        value: toNumber(item.sjzj),
      }))
    : []
  return { ...(res as any), data }
}

export type {
  PurchaseInfoParams,
  PurchaseInfoParam,
  AnnualProcurementVehicle,
  AnnualSalesVehicle,
  SalesCustomer,
  PurchaseCustomer,
  CustomerModelParam,
}